<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/layer/2.3/layer.js"></script>
  <style>
    .content {
      display: flex;
      justify-content: space-around;
    }
  </style>
</head>
<body>
  <div id="root">
    <div>
      <button id="updateData">更新疫情数据,请勿频繁点击</button>
    </div>
    <div class="content">
      <div>
        <h3>国内疫情</h3>
        <table>
          <thead>
            <tr>
              <th>地区</th>
              <th>现存确诊</th>
              <th>累计确诊</th>
              <th>死亡</th>
              <th>治愈</th>
              <th>查看详情</th>
            </tr>
          </thead>
          <tbody id="tbody"></tbody>
        </table>
      </div>
      <div>
        <h3>国际疫情<small>（默认根据累计确诊排序）</small></h3>
        <div>
          <div>
            地区：<select name="" id="continentsSelect">
              <option value="All">全部</option>
              <option value="Asia">亚洲</option>
              <option value="Europe">欧洲</option>
              <option value="Africa">非洲</option>
              <option value="SouthAmerica">南美洲</option>
              <option value="NorthAmerica">北美洲</option>
              <option value="Oceania">大洋洲</option>
            </select>
          </div>
          <div>
            排序：<button id="deadRateRankBtn" data-type="deadRateRank" onclick="getListByCountryArg('deadRateRank', 'asce')">病死率↑</button> | 
            <button id="deadRateRankBtn" data-type="deadRateRank" onclick="getListByCountryArg('deadRateRank', 'desc')">病死率↓</button> |
            <button id="deadCountRankBtn" data-type="deadCountRank" onclick="getListByCountryArg('deadCountRank', 'asce')">累计死亡↑</button> | 
            <button id="deadCountRankBtn" data-type="deadCountRank" onclick="getListByCountryArg('deadCountRank', 'desc')">累计死亡↓</button> | 
            <button id="confirmedCountRankBtn" data-type="confirmedCountRank" onclick="getListByCountryArg('confirmedCountRank', 'asce')">累计确诊↑</button> |
            <button id="confirmedCountRankBtn" data-type="confirmedCountRank" onclick="getListByCountryArg('confirmedCountRank', 'desc')">累计确诊↓</button> |
          </div>
        </div>
        <table>
          <thead>
            <tr>
              <th>地区</th>
              <th>病死率</th>
              <th>排序</th>
              <th>累计死亡</th>
              <th>排序</th>
              <th>累计确诊</th>
              <th>排序</th>
            </tr>
          </thead>
          <tbody id="listByCountryTbody"></tbody>
        </table>
      </div>
    </div>
  </div>

  <script>
    const tbody = document.querySelector("#tbody");
    const listByCountryTbody = document.querySelector("#listByCountryTbody");
    const updateData = document.querySelector("#updateData");
    const continentsSelect = document.querySelector("#continentsSelect");
    const deadRateRankBtn = document.querySelector("#deadRateRankBtn");
    const deadCountRankBtn = document.querySelector("#deadCountRankBtn");
    const confirmedCountRankBtn = document.querySelector("#confirmedCountRankBtn");
    let layerIndex= null;

    function debounce(fn, wait) {
      let timer = null;
      return function(...arg) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.call(this, ...arg)
        }, wait)
      }
    }
    // 获取国内数据
    const getAreaStat = () => {
      return new Promise((resolve, reject) => {
        fetch('http://localhost:4000/api/getAreaStat')
          .then(res => {
            if(res.status !== 200) reject();

            resolve(res.json())
          })
          .catch(err => reject(err))
      })
    }
    
    // 获取指定省份
    const findProvice = (provice) => {
        return new Promise((resolve, reject) => {
          fetch(`http://localhost:4000/api/getAreaStat/${provice}`, {
            method: "POST"
          })
            .then(res => {
              if (res.status !== 200) reject();

              resolve(res.json())
            })
            .catch(err => reject(err))
        })
      }
    
    // 获取全球数据
    const getListByCountryTypeService2true = (arg) => {
      console.log(arg)
      return new Promise((resolve, reject) => {
        fetch('http://localhost:4000/api/getListByCountryTypeService2true', {
          method: "POST",
          headers: { 
            'Accept': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(arg)
        })
          .then(res => {
            if (res.status !== 200) reject();

            resolve(res.json())
          })
          .catch(err => reject(err))
      })
    }

    function renderAreaStatTable (data) {
      let resultStr = '';
      if(Array.isArray(data) && data.length) {
        resultStr = data.reduce((a, b) => {
          let str = '';
          str += a;
          str += `<tr>
            <td>${b.provinceName}</td>
            <td>${b.currentConfirmedCount}</td>
            <td>${b.confirmedCount}</td>
            <td>${b.deadCount}</td>
            <td>${b.curedCount}</td>
            <td><button onclick="viewDetail('${b.provinceName}')">查看详情</button></td>
            </tr>`;

            return str;
        }, '')
      }

      tbody.innerHTML = resultStr;
    }

    function renderListByCountry(data) {
      let resultStr = '';
      if (Array.isArray(data) && data.length) {
        resultStr = data.reduce((a, b) => {
          let str = '';
          str += a;
          str += `<tr>
            <td>${b.provinceName}</td>
            <td>${b.deadRate}</td>
            <td>${b.deadRateRank}</td>
            <td>${b.deadCount}</td>
            <td>${b.deadCountRank}</td>
            <td>${b.confirmedCount}</td>
            <td>${b.confirmedCountRank}</td>
            </tr>`;

          return str;
        }, '')
      }

      listByCountryTbody.innerHTML = resultStr;
    }

    function getLayerContent(cities) {
      return new Promise((resolve, reject) => {
        let bodyStr = '暂无数据';
        if(Array.isArray(cities) && cities.length) {
          bodyStr = cities.reduce((a, b) => {
            let str = '';
            str += a;
            str += `
              <tr>
                <td>${b.cityName}</td>
                <td>${b.currentConfirmedCount}</td>
                <td>${b.confirmedCount}</td>
                <td>${b.deadCount}</td>
                <td>${b.curedCount}</td>
              </tr>
            `;
            return str;
          }, '')
        };

        let resultStr = `
          <div style="padding: 10px">
            <table>
              <thead>
                <tr>
                  <th>地区</th>
                  <th>现存确诊</th>
                  <th>累计确诊</th>
                  <th>死亡</th>
                  <th>治愈</th>
                </tr>  
              </thead>
              <tbody>${bodyStr}</tbody>
            </table>
          </div>
        `;
        resolve(resultStr);
      })
    }

    function viewDetail(provinceName) {
      findProvice(provinceName)
        .then(res => {
          console.log(res);
          layerIndex !== null && layer.close(layerIndex);

          getLayerContent(res.data[0].cities)
            .then(content => {
              layerIndex = layer.open({
                type: 1, // layer类型 0.信息框默认 1.页面层 2.iframe层 3.加载层 4.tips层
                id: 'detailTable',
                title: provinceName,
                area: ['20%', '50%'],
                offset: 'auto',
                moveOut: true,
                shade: 0,
                closeBtn: 1,
                btn: '',
                maxmin: true, // 最大最小化按钮是否显示
                resize: true, // 是否可以调整大小
                content: content || "",
                btnAlign: 'c',
                cancel: function (index, layero) {
                  layer.close(index);
                },
                success: function () { }
              })
            })
            .catch(err => cosnole.error(err))
        })
        .catch(err => {
          console.log(err)
        })
    }

    // 获取全球疫情参数修改
    function getListByCountryArg(type, value) {
      // continents, orderQuery, pageNum, pageSize
      const arg = {
        continents: "全部",
        orderQuery: {
          confirmedCount: -1
        },
        pageNum: 0,
        pageSize: 10 // limit
      };

      switch(type) {
        case 'continents':
          arg['continents'] = value;
          break;
        case 'deadRateRank':
          arg['orderQuery'] = { deadRateRank: value === 'asce' ? 1 : -1};
          break;
        case 'deadCountRank':
          arg['orderQuery'] = { deadCountRank: value === 'asce' ? 1 : -1 };
          break;
        case 'confirmedCountRank':
          arg['orderQuery'] = { confirmedCountRank: value === 'asce' ? 1 : -1 };
          break;
        default:
          break;
      }

      return arg;
    }

    window.onload = async function() {
      try {
        const listByCountryArg = getListByCountryArg();
        
        let areaStatData = await getAreaStat();
        let listByCountryData = await getListByCountryTypeService2true({
          ...listByCountryArg
        });
        renderAreaStatTable(areaStatData);
        renderListByCountry(listByCountryData);

        // 如果手动更新数据源数据，debounce 5s ，防止对数据源数据造成压力
        updateData.addEventListener('click', debounce(() => {
          fetch('/refresh')
            .then(res => {
              if (res.status !== 200) throw error('数据更新失败')
              res.json()
                .then(async ({code, msg}) => {
                  if(Number.parseInt(code) === 200) {
                    alert(msg || "数据更新成功");
                    let areaStatData = await getAreaStat();
                    let listByCountryData = await getListByCountryTypeService2true();
                    renderAreaStatTable(areaStatData);
                    renderListByCountry(listByCountryData);
                    return;
                  }

                  alert(msg)
                })
            })
            .catch(err => {
              alert(err)
            })
        }, 5000));

      } catch (error) {
        console.log(error)
      }
    }
  </script>
</body>
</html>